package com.translate.commons.utils;

import java.lang.reflect.Field;

/**
 * 反射的工具类
 * 也可以用其他工具包封装好的
 * 我这里写了一些自定义的方法，不想再去看那么多工具包的实现了
 * 就直接用自己的了
 * 后面如果想自己加方法也可写在这
 */
public class ReflectDefinedUtil {

    public static <T> String getStr(T obj, Field field) {
        Object val = getVal(obj, field);
        if (val instanceof String) {
            return (String) val;
        }
        return null;
    }

    public static <T> Object getVal(T obj, Field field) {
        if (obj == null) {
            return null;
        }
        if (field == null) {
            return null;
        }
        try {
            field.setAccessible(true);
            Object resObject = field.get(obj);
            return resObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> void setVal(T obj, Field field, Object val) {
        if (obj == null) {
            return;
        }
        try {
            if (field == null) {
                return;
            }
            field.setAccessible(true);
            field.set(obj, val);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static <T> Integer getInt(T obj, Field field) {
        Object val = getVal(obj, field);
        if (val == null) {
            return null;
        }
        if (val instanceof Integer) {
            return (Integer) val;
        }
        return null;
    }

    public static Field getField(Class clazz, String field) {
        if (clazz == null) {
            return null;
        }
        if (field == null || field.trim().length() == 0) {
            return null;
        }
        Class sup = clazz;
        for (int i = 0; i < 5; i++) {
            try {
                Field fi = sup.getDeclaredField(field);
                if (fi != null) {
                    return fi;
                }
                sup = sup.getSuperclass();
                if (sup == null) {
                    break;
                }
            } catch (Exception e) {
                try {
                    sup = sup.getSuperclass();
                } catch (Exception e2) {
                    break;
                }
                e.printStackTrace();
            }
        }
        return null;
    }

}
